package com.lagou.rocket.consumer;

import com.lagou.rocket.entity.Stock;
import com.lagou.rocket.entity.StockOrder;
import com.lagou.rocket.mapper.StockMapper;
import com.lagou.rocket.mapper.StockOrderMapper;
import com.lagou.rocket.service.OrderService;
import com.lagou.rocket.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class Schedul {


    //订单未支付超时时间
    private static long ORDER_EXPIRE = 1;

    @Autowired
    StockOrderMapper stockOrderMapper;

    @Autowired
    StockMapper stockMapper;

    @Autowired
    StockService stockService;

    @Scheduled(cron = "0/2 * * * * ?")
    public void scanOrder(){
        List<StockOrder> stockOrdersList = stockOrderMapper.selectByStatusy(0);
        stockOrdersList.forEach(stockOrder -> {
            long time = stockOrder.getCreateTime().getTime();
            long expire = System.currentTimeMillis() - time;
            if(expire - ORDER_EXPIRE * 60 * 1000 >= 0){
                System.out.println(expire);
                //订单状态：0 未支付 1 已支付 2 超时
                stockOrder.setStatus(2);
                stockOrderMapper.updateByPrimaryKeySelective(stockOrder);
                Stock stock = stockMapper.selectByPrimaryKey(stockOrder.getSid());
                stock.setSale(stock.getSale() - 1);
                stockMapper.updateByPrimaryKeySelective(stock);
                stockService.setStockCountCache(stockOrder.getSid(),stock.getCount() - stock.getSale());
                log.error("111111111111111");
            }
        });
    }
}
